# -*- coding: utf-8 -*-
'''
Created on 2013-4-11

@author: cl.lam
'''
import traceback
import flask
from flask import current_app as app
from flask import g, render_template, flash, session, redirect, url_for, request, request_finished, jsonify
from flask.blueprints import Blueprint

from sys2do.views import BasicView
from sys2do.util.decorator import templated, loginRequired, allPermission
from sys2do.model import db
from sys2do.model.master import Member
from sys2do.model.system import SysLog

from sys2do.util.logic_helper import getCurrentShopID, getCurrentShop, checkLogin
from sys2do.util.common import _g
from sys2do.constant import *

from ext.view import extract_inline_list

__all__ = ['bpMem']


bpMem = Blueprint( 'bpMem', __name__, )

@bpMem.before_request
def addActivetab():
    session[TAB_FLAG] = TAB_HOME

@bpMem.before_request
def _b():
    return checkLogin()

class MemberView( BasicView ):

    template_folder = 'mem'

    @templated( "index.html" )
    def index( self ):
        form = None
        if request.method == 'POST':
            form = SrhForm( request.form )
            session[url_for( '.view' )] = form
        else:
            form = session.get( url_for( '.view' ), SrhForm( request.form ) )
        form.url = url_for( '.view' )
        cds = [Member.shopID == getCurrentShopID(), Member.active == ACTIVE]
        if form.no.data: cds.append( Member.no.like( '%%%s%%' % form.no.data ) )
        if form.name.data: cds.append( Member.name.like( '%%%s%%' % form.name.data ) )
        if form.tel.data: cds.append( Member.no.like( '%%%s%%' % form.tel.data ) )
        return {'result': Member.findBy( cds ), 'form': form}

    @templated( 'add.html' )
    def add( self ):
        obj = Member.init()
        return {'shop': getCurrentShop(), 'obj': obj, 'fromAction': 'add'}

    @templated( 'add.html' )
    def edit( self ):
        obj = Member.getBy( [Member.id == _g( 'id' )] )
        return {'shop': getCurrentShop(), 'obj': obj, 'fromAction': 'edit'}

    @templated( 'view.html' )
    def view( self ):
        obj = Member.getBy( [Member.id == _g( 'id' )] )
        return {'shop': getCurrentShop(), 'obj': obj}

    @templated( 'view_log.html' )
    def viewLog( self ):
        obj = Member.getBy( [Member.id == _g( 'id' )] )
        return {'shop': getCurrentShop(), 'obj': obj}

    @templated( 'view_so.html' )
    def viewSO( self ):
        obj = Member.getBy( [Member.id == _g( 'id' )] )
        return {'shop': getCurrentShop(), 'obj': obj}

    def save( self ):
        if request.method == 'POST':
            kw = request.form.to_dict()
            kw = extract_inline_list( 'mem', **kw )
            obj = None
            try:
                if kw['fromAction'] == 'add':
                    obj = Member.saveNew( **kw['mem'] )
                    db.add( SysLog( refClz = obj.__class__.__name__, type = LOG_TYPE_CREATE, refID = obj.id, ) )
                    flash( MSG_SAVE_SUCC, MESSAGE_INFO )
                elif kw['fromAction'] == 'edit':
                    obj = Member.get( kw['mem']['id'] )
                    obj.saveEdit( **kw['mem'] )
                    db.add( SysLog( refClz = obj.__class__.__name__, type = LOG_TYPE_UPDATE, refID = obj.id, ) )
                    flash( MSG_UPDATE_SUCC, MESSAGE_INFO )
                db.commit()
                return redirect( url_for( '.view', action = 'view', id = obj.id ) )
            except Exception, e:
                flash( MSG_SERVER_ERROR, MESSAGE_ERROR )
                self._error( traceback.format_exc() )
                db.rollback()
                return redirect( url_for( '.view', action = 'index' ) )
        else:
            return redirect( url_for( '.view', action = 'index' ) )

    def searchMem( self ):
        return jsonify( members = [i.no for i in Member.findBy( shopID = getCurrentShopID() )] )

    def getMem( self ):
        member = Member.getBy( [Member.no == _g( 'no' )] )
        return jsonify( product = ( member.toJson() if member else None ) )

bpMem.add_url_rule( '/', view_func = MemberView.as_view( 'view' ), defaults = {'action':'index'} )
bpMem.add_url_rule( '/<action>', view_func = MemberView.as_view( 'view' ) )

from wtforms import Form, TextField, SelectField
from sys2do.util.wt_helper import MyDateField

class SrhForm( Form ):
    no = TextField( u'会员编号', )
    name = TextField( u'姓名', )
    tel = TextField( u'电话', )
